#include "paketitem.h"

PaketItem::PaketItem(QObject *parent, int id) :
    QObject(parent)
{
    this->id = id;
    this->setText(0, (id==-1)?"neues Paket":"Paket "+QVariant(id).toString());
    this->setFlags(Qt::ItemIsEnabled|Qt::ItemIsDropEnabled);
    for ( int i=0; i < 5; i++ )
        this->setFont(i, QFont("" , -1, QFont::Bold));
    this->setData(0, Qt::UserRole, this->id);
}

void PaketItem::removeChild(QTreeWidgetItem *child)
{
    RemiItem *remi = static_cast<RemiItem*>(child);
    remis.removeOne(remi);
    updateOverview();
    QTreeWidgetItem::removeChild(remi);
}

void PaketItem::addChild(QTreeWidgetItem *child)
{
    RemiItem *remi = static_cast<RemiItem*>(child);
    remis.append(remi);
    connect(remi, SIGNAL(deleteItem(RemiItem*)), this, SLOT(deleteRemi(RemiItem*)));
    connect(remi, SIGNAL(itemChanged()), this, SLOT(updateOverview()));
    updateOverview();
    QTreeWidgetItem::addChild(remi);
}

int PaketItem::getID() const
{
    return id;
}

void PaketItem::setID(int id)
{
    this->id = id;
}

void PaketItem::addRemi(RemiItem *item)
{
    foreach ( RemiItem *r, remis )
    {
        if ( r->getGTIN() == item->getGTIN() && r->getAddon() == item->getAddon() )
        {
            /** Die gleiche Remi existiert bereits in dem Paket, es wird zusammengeführt **/
            r->addQuantity( item->getQuantity() );
            item->deleteRemi();
            return;
        }
    }

    item->setPaket(id);
    addChild(item);
}

void PaketItem::deleteRemi(RemiItem *item)
{
    removeChild(item);
    item->deleteRemi();
    emitDataChanged();
}

QList<RemiItem*> PaketItem::getRemiItems()
{
    return remis;
}

void PaketItem::updateOverview()
{
    if ( !remis.empty() )
    {
        int quantity = 0;
        float preis = 0.0;
        foreach ( RemiItem *r, remis )
        {
            quantity += r->getQuantity();
            preis += ( r->getPreis() * r->getQuantity() );
        }
        setText(3, QVariant(quantity).toString());
        setText(4, QString("%L1 €").arg(preis,0,'f',2));
    }
    else
    {
        setText(3, QString());
        setText(4, QString());
    }
}
